<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\Jingshu as JingshuModel;
use app\common\model\JingshuProgress as JingshuProgressModel;

/**
 * 经书控制器
 * Class Jingshu
 * @package app\home\controller
 */
class Jingshu extends Base
{
    /**
     * [index  列表]
     * @param
     * @return json
     * @author [C。]
     */
    public function index()
    {
        $param = input('param.');
        $model = new JingshuModel();
        $pmodel = new JingshuProgressModel();
        $this->getPageAndSize($param);
        $map = [];
        $user = $this->user;
        try{
            $map['status'] = 1;
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getlist($map,$this->from, $this->size,'id,title');
            foreach($lists as &$v){
                $v['finish_num'] = $pmodel->getAllCount(['mid'=>$user['id'],'status'=>1,'jid'=>$v['id']]);
                $progress = $pmodel->findOne(['mid'=>$user['id'],'status'=>2,'jid'=>$v['id']],'id,number');
                $jingshu = $model->findData($v['id'],'id','number');
                if(!empty($progress)){
                    $v['progress'] = round($progress['number'] / $jingshu['number'],4) * 100;
                    $v['number'] = $progress['number'];
                    $v['pid'] = $progress['id'];
                }else{
                    $v['progress'] = 0;
                    $v['number'] = 0;
                }
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [get  根据id获取]
     * @param
     * @return json
     * @author [C。]
     */
    public function get()
    {
        $param = input('param.');
        $model = new JingshuModel();
        $pmodel = new JingshuProgressModel();
        $user = $this->user;
        try{
            $data = $model->findData($param['id'],'id','id,content,number');
            $data['content'] = str_replace(array("\r\n", "\r", "\n"," "),'',$data['content']);
            $progress = $pmodel->findOne(['jid'=>$data['id'],'mid'=>$user['id'],'status'=>2],'id,number');
            if(!empty($progress)){
                $data['pid'] = $progress['id'];
                $data['cnumber'] = $progress['number'];
            }else{
                $data['cnumber'] = 0;
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$data);
    }
}